package com.xaicode.auth.config.mybatisplus;

import cn.hutool.core.util.StrUtil;
import com.xaicode.auth.security.AuthConst;
import com.xaicode.auth.security.LoginUtil;
import com.xaicode.auth.security.domain.LoginUser;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 元对象字段填充控制器抽象类，实现公共字段自动写入
 * 
 * @date 2024/8/9
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 软删除标识
        // 0 正常
        // 1 删除
        this.setFieldValByName("deleted", AuthConst.DEL_FLAG_NORMAL /* 0 */, metaObject);

        // 时间类
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);

        if (checkIfPassCreator(metaObject)) {
            return;
        }

        try {
            LoginUser loginUser = LoginUtil.getLoginUser();
            if (Objects.isNull(loginUser)) {
                this.setFieldValByName("createBy", "", metaObject);
                this.setFieldValByName("updateBy", "", metaObject);
            } else {
                this.setFieldValByName("createBy", loginUser.getUserId(), metaObject);
                this.setFieldValByName("updateBy", loginUser.getUserId(), metaObject);
            }
        } catch (Exception e) {
            log.error("[MyMetaObjectHandler][InsertFill] 获取用户信息失败：{}", e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 时间类
        this.setFieldValByName("updateTime", new Date(), metaObject);

        if (checkIfPassUpdater(metaObject)) {
            return;
        }

        try {
            LoginUser loginUser = LoginUtil.getLoginUser();
            if (Objects.isNull(loginUser)) {
                this.setFieldValByName("updateBy", "", metaObject);
            } else {
                this.setFieldValByName("updateBy", loginUser.getUserId(), metaObject);
            }
        } catch (Exception e) {
            log.error("[MyMetaObjectHandler][UpdateFill] 获取用户信息失败：{}", e.getMessage());
        }
    }

    // ----

    private final String[] ignores = new String[]{
            "程序调用"
    };

    private boolean checkIfPassCreator(MetaObject metaObject) {
        Object o = metaObject.getValue("createBy");
        return StrUtil.containsAnyIgnoreCase(String.valueOf(o), ignores);
    }

    private boolean checkIfPassUpdater(MetaObject metaObject) {
        Object o = metaObject.getValue("updateBy");
        return StrUtil.containsAnyIgnoreCase(String.valueOf(o), ignores);
    }
}
